/**
 * Created with hong.rong
 * Description:*
 * Date:2020/06/25
 */

import React, { Suspense, useEffect, useState, useRef } from 'react'
import { EllipsisOutlined } from '@ant-design/icons'
import { Col, Dropdown, Menu, Row } from 'antd'
import { GridContent } from '@ant-design/pro-layout'
import { connect } from 'umi'
import PageLoading from './components/PageLoading'
import { getTimeDistance } from './utils'
import { fakeChartData } from '@/services/dashboard'
import styles from './style.less'

const IntroduceRow = React.lazy(() => import('./components/IntroduceRow'))
const SalesCard = React.lazy(() => import('./components/SalesCard'))
const TopSearch = React.lazy(() => import('./components/TopSearch'))
const ProportionSales = React.lazy(() => import('./components/ProportionSales'))
const OfflineData = React.lazy(() => import('./components/OfflineData'))

export default function Dashboard() {
  const dataRef = useRef()
  const [loading, setLoading] = useState(false)
  const [rangePickerValue, setRangePickerValue] = useState(
    getTimeDistance('year')
  )
  const [dataSource, setDataSource] = useState({
    visitData: [],
    salesData: [],
  })

  useEffect(() => {
    // dataRef.current = requestAnimationFrame(() => {
    //   fetchData()
    // })
    // return () => {
    //   cancelAnimationFrame(dataRef.current)
    // }
  }, [])

  const fetchData = async () => {
    setLoading(true)
    const { data = {} } = await fakeChartData()
    setDataSource(data)
    setTimeout(() => {
      setLoading(false)
    }, 1500)
  }

  const handleRangePickerChange = async rangePickerValue => {
    setRangePickerValue(rangePickerValue)
    await fetchData()
  }

  const selectDate = async type => {
    setRangePickerValue(getTimeDistance(type))
    await fetchData()
  }

  const isActive = type => {
    if (!rangePickerValue) {
      return ''
    }
    const value = getTimeDistance(type)
    if (!value) {
      return ''
    }
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return ''
    }
    if (
      rangePickerValue[0].isSame(value[0]) &&
      rangePickerValue[1].isSame(value[1])
    ) {
      return styles.currentDate
    }
    return ''
  }

  const { visitData = [], salesData = [] } = dataSource

  return (
    <GridContent>
      <React.Fragment>
        <Suspense fallback={<PageLoading />}>
          <IntroduceRow loading={loading} visitData={visitData} />
        </Suspense>
        <Suspense fallback={null}>
          <SalesCard
            rangePickerValue={rangePickerValue}
            salesData={salesData}
            isActive={isActive}
            handleRangePickerChange={handleRangePickerChange}
            loading={loading}
            selectDate={selectDate}
          />
        </Suspense>
      </React.Fragment>
    </GridContent>
  )
}
